package movee.spring.app.template.io.wall;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.Arrays;

import static org.springframework.http.HttpMethod.POST;

/**
 * 使用 RestTemplate 请求http
 *
 * @author movee
 */
@Slf4j
public class WallClient {


    private static final String WALL_CASE_PATH = "/handlers/wall_case_query";

    private final RestTemplate restTemplate;
    private final String baseUrl;
    private final HttpHeaders headers;

    private final Gson gson = new Gson();

    public WallClient(String uri, Long connectTimeoutMs) {

        this.baseUrl = uri;
        this.headers = new HttpHeaders();
        this.headers.setContentType(MediaType.APPLICATION_JSON);
        this.headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

        this.restTemplate = new RestTemplateBuilder()
                .setConnectTimeout(Duration.ofMillis(connectTimeoutMs))
                .setReadTimeout(Duration.ofSeconds(connectTimeoutMs))
                .build();

    }


    public WallCaseMsg getWallCase(String startTime, String endTime) {

        /*
         * 返回format：
         *   {
         *       "status": 0,
         *       "message": {},
         *   }
         */
        String url = baseUrl + WALL_CASE_PATH;
        try {
            WallCaseRequest request = WallCaseRequest.of(512, startTime, endTime);
            HttpEntity<String> requestHttpEntity = new HttpEntity<>(gson.toJson(request), headers);

            log.debug("getWallCase request body: {}", gson.toJson(request));
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, POST, requestHttpEntity, String.class);

            log.debug("getWallCase response body: {}", responseEntity.getBody());
            if (responseEntity.getBody() != null) {
                JsonObject response = (JsonObject) JsonParser.parseString(responseEntity.getBody());

                if (response.has("status")
                        && response.getAsJsonPrimitive("status").getAsInt() == 0) {

                    return gson.fromJson(responseEntity.getBody(), WallCaseMsg.class);
                } else {
                    log.warn("getWallCase failed, startTime: {}", startTime);
                }
            } else {
                log.warn("getWallCase failed, startTime: {}, response body is null", startTime);
            }
        } catch (Exception e) {
            log.error("getWallCase failed, startTime: {}, exception stack: {}",
                    startTime, ExceptionUtils.getStackTrace(e));
        }

        return null;

    }

}

